package com.liang.gulimall.order.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.common.execption.NoStockException;
import com.liang.common.to.mq.OrderTo;
import com.liang.common.to.mq.SeckillOrderTo;
import com.liang.common.utils.PageUtils;
import com.liang.common.utils.Query;
import com.liang.common.utils.R;
import com.liang.common.vo.MemberVo;
import com.liang.gulimall.order.constant.OrderConstant;
import com.liang.gulimall.order.dao.OrderDao;
import com.liang.gulimall.order.entity.OrderEntity;
import com.liang.gulimall.order.entity.OrderItemEntity;
import com.liang.gulimall.order.entity.PaymentInfoEntity;
import com.liang.gulimall.order.enume.OrderStatusEnum;
import com.liang.gulimall.order.feign.CartFeignService;
import com.liang.gulimall.order.feign.MemberFeignService;
import com.liang.gulimall.order.feign.ProductFeignService;
import com.liang.gulimall.order.feign.WareFeignService;
import com.liang.gulimall.order.interceptor.LoginUserInterceptor;
import com.liang.gulimall.order.service.OrderItemService;
import com.liang.gulimall.order.service.OrderService;
import com.liang.gulimall.order.service.PaymentInfoService;
import com.liang.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    MemberFeignService memberFeignService;
    @Resource
    private CartFeignService cartFeignService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    PaymentInfoService paymentInfoService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        MemberVo memberVo = LoginUserInterceptor.loginUserThread.get();//同一线程共享数据信息
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //拿到主线程请求，放到各个异步任务中
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//

        CompletableFuture<Void> addrFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程调用查地址
            List<MemberReceiveAddressVo> address = memberFeignService.getAddress(memberVo.getId());
            orderConfirmVo.setAddressVos(address);
        }, threadPoolExecutor);

        CompletableFuture<Void> itemFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程调用查选中的商品
            List<OrderItemVo> userCheckedItem = cartFeignService.getUserCheckedItem();
            orderConfirmVo.setItemVos(userCheckedItem);
        }, threadPoolExecutor).thenRunAsync(() -> {
            List<OrderItemVo> itemVos = orderConfirmVo.getItemVos();
            List<Long> skuIds = itemVos.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wareFeignService.hasStock(skuIds);
            if (r.getCode() == 0) {
                List<SkuHasStockVo> hasStockVos = r.getData("data", new TypeReference<List<SkuHasStockVo>>() {
                });
                if (hasStockVos != null) {
                    Map<Long, Boolean> skuStock = hasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                    orderConfirmVo.setHasStock(skuStock);
                }
            }
        }, threadPoolExecutor);
        //积分
        orderConfirmVo.setIntegration(memberVo.getIntegration());
        CompletableFuture.allOf(addrFuture, itemFuture).get();
        //其他数据自动计算
        //TODO 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        orderConfirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId(),
                token, 30, TimeUnit.MINUTES);

        return orderConfirmVo;
    }

    //@GlobalTransactional    //定义全局事务的范围：开始全局事务、提交或回滚全局事务
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(SubmitOrderVo submitOrderVo) {
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        MemberVo memberVo = LoginUserInterceptor.loginUserThread.get();
        /**
         * 令牌的比较和删除要保证原子性
         * lua脚本，返回1成功，0失败
         */
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId()), submitOrderVo.getOrderToken());
        if (result == 0L) {
            //验证失败
            responseVo.setCode(1);
        } else {
            //验证成功
            //生成订单
            OrderCreateVo orderCreateVo = createOrder(memberVo, submitOrderVo);
            //验价
            OrderEntity order = orderCreateVo.getOrder();
            BigDecimal payAmount = order.getPayAmount();
            BigDecimal payPrice = submitOrderVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                //验价成功
                //保存订单
                saveOrder(orderCreateVo);
                //锁定库存
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrderSn());
                List<OrderItemVo> collect = orderCreateVo.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(collect);
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode()==0){
                    //锁成功了
                    responseVo.setOrderEntity(order);
                    //int i=10/0;//订单回滚，库存不滚
                    //订单创建成功，发送消息到MQ
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order);
                }else {
                    responseVo.setCode(3);
                    throw new NoStockException((String) r.get("msg"));
                    //失败
                }
            }else {
                //验价失败
                responseVo.setCode(2);
            }
        }
        return responseVo;
    }

    /**
     * 关闭订单
     * @param orderEntity
     */
    @Override
    public void orderClose(OrderEntity orderEntity) {
        //获取订单的最新状态
        OrderEntity order = this.baseMapper.selectById(orderEntity);
        if (order.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            order.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.baseMapper.updateById(order);
            //防止订单服务不稳定，库存先判断解锁
            try {//TODO 保证消息一定要发送
                OrderTo orderTo = new OrderTo();
                BeanUtils.copyProperties(order,orderTo);
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e){
                //TODO 没有发送的消息重试
            }
        }
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberVo memberVo = LoginUserInterceptor.loginUserThread.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> entityList = page.getRecords().stream().map(orderEntity -> {
            //注入订单项
            List<OrderItemEntity> itemEntities = getOrderItemByOrderSn(orderEntity.getOrderSn());
            orderEntity.setOrderItemEntities(itemEntities);
            return orderEntity;
        }).collect(Collectors.toList());
        page.setRecords(entityList);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(vo.getOut_trade_no());
        paymentInfo.setCreateTime(vo.getGmt_create());
        paymentInfo.setPaymentStatus(vo.getTrade_status());
        paymentInfo.setAlipayTradeNo(vo.getTrade_no());
        paymentInfo.setCallbackContent(JSONObject.toJSONString(vo));
        paymentInfo.setCallbackTime(vo.getNotify_time());
        paymentInfo.setTotalAmount(new BigDecimal(vo.getTotal_amount()));
        paymentInfo.setConfirmTime(vo.getGmt_payment());
        paymentInfo.setSubject(vo.getSubject());
        try {
            paymentInfoService.save(paymentInfo);
        }catch (Exception e){
            return "error";
        }
        //修改订单状态
        //获取当前状态
        String tradeStatus = vo.getTrade_status();
        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = vo.getOut_trade_no(); //获取订单号
            this.baseMapper.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode(),vo.getGmt_payment());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo orderTo) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = orderTo.getSeckillPrice().multiply(BigDecimal.valueOf(orderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //保存订单
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(orderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);

        orderItem.setSkuQuantity(orderTo.getNum());

        //保存商品的spu信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(orderTo.getSkuId());
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItem.setSpuId(spuInfoData.getId());
        orderItem.setSpuName(spuInfoData.getSpuName());
        //orderItem.setSpuBrand(spuInfoData.getBrandName());
        orderItem.setCategoryId(spuInfoData.getCatalogId());

        //保存订单项数据
        orderItemService.save(orderItem);
    }

    private List<OrderItemEntity> getOrderItemByOrderSn(String orderSn) {
        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        return list;
    }

    /**
     * 保存订单和订单项信息
     * @param orderCreateVo
     */
    private void saveOrder(OrderCreateVo orderCreateVo) {
        OrderEntity order = orderCreateVo.getOrder();
        order.setCreateTime(new Date());
        order.setModifyTime(new Date());
        System.out.println(new Date());
        baseMapper.insert(order);
        //获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateVo.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 分步骤创建订单
     * @return
     */
    private OrderCreateVo createOrder(MemberVo memberVo,SubmitOrderVo submitOrderVo){
        OrderCreateVo orderCreateVo = new OrderCreateVo();
        OrderEntity orderEntity = new OrderEntity();
        String orderId = IdWorker.getTimeId();//生成订单号
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setOrderSn(orderId);
        orderEntity.setMemberId(memberVo.getId());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setMemberUsername(memberVo.getUsername());
        //运费，收货地址信息
        R fare = wareFeignService.getFare(submitOrderVo.getAddrId());
        FareVo data = fare.getData("data", new TypeReference<FareVo>() {
        });
        orderEntity.setFreightAmount(data.getFare());
        orderEntity.setReceiverName(data.getAddressVo().getName());
        orderEntity.setReceiverPhone(data.getAddressVo().getPhone());
        orderEntity.setReceiverPostCode(data.getAddressVo().getPostCode());
        orderEntity.setReceiverProvince(data.getAddressVo().getProvince());
        orderEntity.setReceiverCity(data.getAddressVo().getCity());
        orderEntity.setReceiverRegion(data.getAddressVo().getRegion());
        orderEntity.setReceiverDetailAddress(data.getAddressVo().getDetailAddress());

        //再查一次购物车,获取购物项，防止购物车价格，数量改变
        List<OrderItemVo> userCheckedItem = cartFeignService.getUserCheckedItem();
        List<OrderItemEntity> orderItemEntities = userCheckedItem.stream().map(orderItemVo -> {
            OrderItemEntity orderItemEntity = buildOrderItemEntity(orderItemVo);
            orderItemEntity.setOrderSn(orderId);
            return orderItemEntity;
        }).collect(Collectors.toList());
        //订单项（已优惠）累加
        BigDecimal total = new BigDecimal("0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            BigDecimal realAmount = orderItemEntity.getRealAmount();
            total = total.add(realAmount);
            //优惠价格信息
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            intergration = intergration.add(orderItemEntity.getIntegrationAmount());
            //积分信息和成长值信息
            integrationTotal += orderItemEntity.getGiftIntegration();
            growthTotal += orderItemEntity.getGiftGrowth();
        }
        orderEntity.setTotalAmount(total);
        //应付额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(intergration);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);
        orderEntity.setDeleteStatus(0);

        orderCreateVo.setOrder(orderEntity);
        orderCreateVo.setOrderItems(orderItemEntities);
        return orderCreateVo;
    }

    /**
     * 构建订单项
     *
     * @param orderItemVo
     * @return
     */
    private OrderItemEntity buildOrderItemEntity(OrderItemVo orderItemVo) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //订单信息
        //spu信息
        R spuInfoR = productFeignService.getSpuInfoBySkuId(orderItemVo.getSkuId());
        SpuInfoVo spuInfo = spuInfoR.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfo.getId());
        orderItemEntity.setSpuName(spuInfo.getSpuName());
        orderItemEntity.setCategoryId(spuInfo.getCatalogId());
        orderItemEntity.setSpuBrand(spuInfo.getBrandId().toString());

        //sku信息
        orderItemEntity.setSkuId(orderItemVo.getSkuId());
        String skuAttr = StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuName(orderItemVo.getTitle());
        orderItemEntity.setSkuPic(orderItemVo.getImage());
        orderItemEntity.setSkuPrice(orderItemVo.getPrice());
        orderItemEntity.setSkuQuantity(orderItemVo.getCount());
        //优惠信息

        //积分成长值信息
        orderItemEntity.setGiftGrowth(orderItemVo.getPrice().intValue());
        orderItemEntity.setGiftIntegration(orderItemVo.getPrice().intValue());
        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);
        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

}